import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class YField extends StatefulWidget {
  // 基础TextField参数
  final TextEditingController? controller;
  final InputDecoration? decoration;
  final TextInputType? keyboardType;
  final bool obscureText;

  // 焦点相关
  final FocusNode? focusNode;
  final ValueChanged<bool>? onFocusChanged;
  final VoidCallback? onFocusGained; // 获得焦点回调
  final VoidCallback? onFocusLost; // 失去焦点回调

  // 其他回调
  final ValueChanged<String>? onChanged;
  final ValueChanged<String>? onSubmitted;

  final TextAlign? textAlign;
  final String? hintText;
  final TextStyle? hintStyle;
  final TextStyle? style;

  final int maxLines;
  final int? maxLength;

  final bool enable;
  const YField({
    super.key,
    this.controller,
    this.decoration,
    this.keyboardType,
    this.obscureText = false,
    this.focusNode,
    this.onFocusChanged,
    this.onFocusGained,
    this.onFocusLost,
    this.onChanged,
    this.onSubmitted,
    this.textAlign,
    this.hintStyle,
    this.hintText,
    this.style,
    this.maxLines = 1,
    this.maxLength,
    this.enable = true,
  });

  @override
  State<YField> createState() => _YFieldState();
}

class _YFieldState extends State<YField> {
  late FocusNode _focusNode;
  bool _hasFocus = false;

  @override
  void initState() {
    super.initState();
    _focusNode = widget.focusNode ?? FocusNode();
    _focusNode.addListener(_handleFocusChange);
  }

  void _handleFocusChange() {
    final newFocus = _focusNode.hasFocus;

    if (newFocus != _hasFocus) {
      setState(() => _hasFocus = newFocus);
      widget.onFocusChanged?.call(newFocus);

      if (newFocus) {
        widget.onFocusGained?.call();
      } else {
        widget.onFocusLost?.call();
      }
    }
  }

  @override
  void dispose() {
    _focusNode.removeListener(_handleFocusChange);
    if (widget.focusNode == null) {
      _focusNode.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
      focusNode: _focusNode,
      maxLines: widget.maxLines,
      maxLength: widget.maxLength,
      controller: widget.controller,
      decoration:
          widget.decoration ??
          InputDecoration(hintText: widget.hintText, hintStyle: widget.hintStyle, border: InputBorder.none),
      keyboardType: widget.keyboardType,
      obscureText: widget.obscureText,
      onChanged: widget.onChanged,
      onSubmitted: widget.onSubmitted,
      textAlign: widget.textAlign ?? TextAlign.right,
      style: widget.style,
      cursorColor: Colors.blue,
      enabled: widget.enable,
    );
  }
}
